/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.iasd.youthshelter.datacore.controller;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import pt.iasd.youthshelter.datamodel.ActivityType;
import pt.iasd.youthshelter.datamodel.ActivityParticipation;
import pt.iasd.youthshelter.datamodel.Club;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import org.openide.util.Lookup;
import org.openide.util.lookup.AbstractLookup;
import org.openide.util.lookup.InstanceContent;
import org.openide.util.lookup.ServiceProvider;
import pt.iasd.youthshelter.datacore.EntityManagerSemaphore;
import pt.iasd.youthshelter.datacore.controller.exceptions.IllegalOrphanException;
import pt.iasd.youthshelter.datacore.controller.exceptions.NonexistentEntityException;
import pt.iasd.youthshelter.datacore.events.ActivityRefreshEvent;
import pt.iasd.youthshelter.datamodel.Activity;
import pt.iasd.youthshelter.datamodel.service.ActivityController;

/**
 *
 * @author Rui
 */
@ServiceProvider(service=ActivityController.class)
public class ActivityJpaController implements Serializable, ActivityController {
    private InstanceContent content = new InstanceContent();
    private Lookup lookup = new AbstractLookup(content);

    private EntityManager aquireEntityManager() throws InterruptedException {
        EntityManagerSemaphore.getInstance().getSemaphore().acquire();
        return EntityManagerSemaphore.getInstance().getEntityManager();
    }
    
    private void releaseEntityManager(EntityManager em) {
        if (em != null && em.isOpen()) {
            em.close();
        }
        EntityManagerSemaphore.getInstance().getSemaphore().release();
    }

    @Override
    public void create(Activity activity) {
        if (activity.getActivityParticipationList() == null) {
            activity.setActivityParticipationList(new ArrayList<ActivityParticipation>());
        }
        if (activity.getClubList() == null) {
            activity.setClubList(new ArrayList<Club>());
        }
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            ActivityType typeId = activity.getTypeId();
            if (typeId != null) {
                typeId = em.getReference(typeId.getClass(), typeId.getId());
                activity.setTypeId(typeId);
            }
            List<Club> attachedClubList = new ArrayList<Club>();
            for (Club clubListClubToAttach : activity.getClubList()) {
                clubListClubToAttach = em.getReference(clubListClubToAttach.getClass(), clubListClubToAttach.getId());
                attachedClubList.add(clubListClubToAttach);
            }
            activity.setClubList(attachedClubList);
            List<ActivityParticipation> attachedActivityParticipationList = new ArrayList<ActivityParticipation>();
            for (ActivityParticipation activityParticipationListActivityParticipationToAttach : activity.getActivityParticipationList()) {
                activityParticipationListActivityParticipationToAttach = em.getReference(activityParticipationListActivityParticipationToAttach.getClass(), activityParticipationListActivityParticipationToAttach.getActivityParticipationPK());
                attachedActivityParticipationList.add(activityParticipationListActivityParticipationToAttach);
            }
            activity.setActivityParticipationList(attachedActivityParticipationList);
            em.persist(activity);
            if (typeId != null) {
                typeId.getActivityList().add(activity);
                em.merge(typeId);
            }
            for (Club clubListClub : activity.getClubList()) {
                clubListClub.getActivityList().add(activity);
                clubListClub = em.merge(clubListClub);
            }
            for (ActivityParticipation activityParticipationListActivityParticipation : activity.getActivityParticipationList()) {
                Activity oldActivityOfActivityParticipationListActivityParticipation = activityParticipationListActivityParticipation.getActivity();
                activityParticipationListActivityParticipation.setActivity(activity);
                activityParticipationListActivityParticipation = em.merge(activityParticipationListActivityParticipation);
                if (oldActivityOfActivityParticipationListActivityParticipation != null) {
                    oldActivityOfActivityParticipationListActivityParticipation.getActivityParticipationList().remove(activityParticipationListActivityParticipation);
                    em.merge(oldActivityOfActivityParticipationListActivityParticipation);
                }
            }
            em.getTransaction().commit();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        content.set(Arrays.asList(new ActivityRefreshEvent()), null);
    }

    @Override
    public void edit(Activity activity) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            Activity persistentActivity = em.find(Activity.class, activity.getId());
            ActivityType typeIdOld = persistentActivity.getTypeId();
            ActivityType typeIdNew = activity.getTypeId();
            List<Club> clubListOld = persistentActivity.getClubList();
            List<Club> clubListNew = activity.getClubList();
            List<ActivityParticipation> activityParticipationListOld = persistentActivity.getActivityParticipationList();
            List<ActivityParticipation> activityParticipationListNew = activity.getActivityParticipationList();
            List<String> illegalOrphanMessages = null;
            for (ActivityParticipation activityParticipationListOldActivityParticipation : activityParticipationListOld) {
                if (!activityParticipationListNew.contains(activityParticipationListOldActivityParticipation)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain ActivityParticipation " + activityParticipationListOldActivityParticipation + " since its activity field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (typeIdNew != null) {
                typeIdNew = em.getReference(typeIdNew.getClass(), typeIdNew.getId());
                activity.setTypeId(typeIdNew);
            }
            List<Club> attachedClubListNew = new ArrayList<Club>();
            for (Club clubListNewClubToAttach : clubListNew) {
                clubListNewClubToAttach = em.getReference(clubListNewClubToAttach.getClass(), clubListNewClubToAttach.getId());
                attachedClubListNew.add(clubListNewClubToAttach);
            }
            clubListNew = attachedClubListNew;
            activity.setClubList(clubListNew);
            List<ActivityParticipation> attachedActivityParticipationListNew = new ArrayList<ActivityParticipation>();
            for (ActivityParticipation activityParticipationListNewActivityParticipationToAttach : activityParticipationListNew) {
                activityParticipationListNewActivityParticipationToAttach = em.getReference(activityParticipationListNewActivityParticipationToAttach.getClass(), activityParticipationListNewActivityParticipationToAttach.getActivityParticipationPK());
                attachedActivityParticipationListNew.add(activityParticipationListNewActivityParticipationToAttach);
            }
            activityParticipationListNew = attachedActivityParticipationListNew;
            activity.setActivityParticipationList(activityParticipationListNew);
            activity = em.merge(activity);
            if (typeIdOld != null && !typeIdOld.equals(typeIdNew)) {
                typeIdOld.getActivityList().remove(activity);
                typeIdOld = em.merge(typeIdOld);
            }
            if (typeIdNew != null && !typeIdNew.equals(typeIdOld)) {
                typeIdNew.getActivityList().add(activity);
                em.merge(typeIdNew);
            }
            for (Club clubListOldClub : clubListOld) {
                if (!clubListNew.contains(clubListOldClub)) {
                    clubListOldClub.getActivityList().remove(activity);
                    clubListOldClub = em.merge(clubListOldClub);
                }
            }
            for (Club clubListNewClub : clubListNew) {
                if (!clubListOld.contains(clubListNewClub)) {
                    clubListNewClub.getActivityList().add(activity);
                    clubListNewClub = em.merge(clubListNewClub);
                }
            }
            for (ActivityParticipation activityParticipationListNewActivityParticipation : activityParticipationListNew) {
                if (!activityParticipationListOld.contains(activityParticipationListNewActivityParticipation)) {
                    Activity oldActivityOfActivityParticipationListNewActivityParticipation = activityParticipationListNewActivityParticipation.getActivity();
                    activityParticipationListNewActivityParticipation.setActivity(activity);
                    activityParticipationListNewActivityParticipation = em.merge(activityParticipationListNewActivityParticipation);
                    if (oldActivityOfActivityParticipationListNewActivityParticipation != null && !oldActivityOfActivityParticipationListNewActivityParticipation.equals(activity)) {
                        oldActivityOfActivityParticipationListNewActivityParticipation.getActivityParticipationList().remove(activityParticipationListNewActivityParticipation);
                        em.merge(oldActivityOfActivityParticipationListNewActivityParticipation);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = activity.getId();
                if (findActivity(id) == null) {
                    throw new NonexistentEntityException("The activity with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            releaseEntityManager(em);
        }
        content.set(Arrays.asList(new ActivityRefreshEvent()), null);
    }

    @Override
    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            Activity activity;
            try {
                activity = em.getReference(Activity.class, id);
                activity.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The activity with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<ActivityParticipation> activityParticipationListOrphanCheck = activity.getActivityParticipationList();
            for (ActivityParticipation activityParticipationListOrphanCheckActivityParticipation : activityParticipationListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Activity (" + activity + ") cannot be destroyed since the ActivityParticipation " + activityParticipationListOrphanCheckActivityParticipation + " in its activityParticipationList field has a non-nullable activity field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            ActivityType typeId = activity.getTypeId();
            if (typeId != null) {
                typeId.getActivityList().remove(activity);
                em.merge(typeId);
            }
            List<Club> clubList = activity.getClubList();
            for (Club clubListClub : clubList) {
                clubListClub.getActivityList().remove(activity);
                em.merge(clubListClub);
            }
            em.remove(activity);
            em.getTransaction().commit();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        content.set(Arrays.asList(new ActivityRefreshEvent()), null);
    }

    @Override
    public List<Activity> findActivityEntities() {
        return findActivityEntities(true, -1, -1);
    }

    @Override
    public List<Activity> findActivityEntities(int maxResults, int firstResult) {
        return findActivityEntities(false, maxResults, firstResult);
    }

    private List<Activity> findActivityEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Activity.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public List<Activity> findCurrentActivityEntities() {
        return findCurrentActivityEntities(true, -1, -1);
    }

    @Override
    public List<Activity> findCurrentActivityEntities(int maxResults, int firstResult) {
        return findCurrentActivityEntities(false, maxResults, firstResult);
    }

    private List<Activity> findCurrentActivityEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery cq = cb.createQuery();
            Root<Activity> root = cq.from(Activity.class);
            cq.select(root);
            cq.where(cb.greaterThanOrEqualTo(root.get(root.getModel().getSingularAttribute("endDate", Date.class)), cb.currentDate()));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public Activity findActivity(Integer id) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            return em.find(Activity.class, id);
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public int getActivityCount() {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Activity> rt = cq.from(Activity.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return 0;
    }

    @Override
    public Lookup getLookup() {
        return lookup;
    }
}
